<template>
<div class='company-list bg-white'>
  <div class="relative-position full-height page-content">
    <collapse ref="collapse">
      <template v-slot:content>
        <q-form class="toolbar" @submit.prevent="onSearchByFilters" style="margin-top: 6px">
          <!-- 工具栏上层 -->
          <div class="form-inline top">
            <q-select class="select"
                      outlined dense emit-value map-options options-dense
                      :options="statusOptions"
                      :loading="isStatusOptionsLoading"
                      v-model="queryParams.status"
            >
              <template v-slot:before>
                <span class="form-name">状态：</span>
              </template>
            </q-select>
            <q-space/>
            <div class="right box">
              <q-btn class="btn margin-r-10" outline color="primary"
                     label="重置" @click="resetSearch"/>
              <q-btn class="btn" unelevated type="submit" color="primary" label="查询" />
            </div>
          </div>
          <div class="form-inline bottom">
            <div class="left box">
              <q-btn class="margin-r-10" outline color="primary"
                     :disable="selected.length === 0"
                     @click="onBatchDeleteClick" label="批量删除" />
              <q-btn class="margin-r-10" outline color="primary" label="添加用户"
                     @click="openCompanyDialog('add')" />
            </div>
            <q-space/>
            <div class="right box">
              <select-input ref="selectInput"
                :list="queryConditions"
                @search="onSearchByKeyword"
                @clearSearchVal="clearSearchVal"
              />
            </div>
          </div>
        </q-form>
      </template>
    </collapse>
    <q-table
      :data="tableData" :columns="columns"
      row-key="id" class="scroll myTable"
      :loading="tableLoading"
      selection="multiple" :selected.sync="selected"
      hide-bottom :pagination="{rowsPerPage: 0}"
      no-data-label="暂无数据" @request="getCompanyList">
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td auto-width>
            <q-checkbox v-model="props.selected"/>
          </q-td>
          <q-td key="name" :props="props">{{ props.row.name }}</q-td>
          <q-td key="administrator" :props="props">{{ props.row.administrator }}</q-td>
          <q-td key="email" :props="props">{{ props.row.email }}</q-td>
          <q-td key="statusLabel" :props="props">{{ props.row.statusLabel }}</q-td>
          <q-td key="operate" :props="props" style="width: 100px">
            <q-btn flat dense round color="primary" icon="iconfont icontubiao-12"
                   @click="openCompanyDialog('edit', props.row)" >
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn flat dense round color="primary" icon="iconfont icontubiao-16"
                   @click="delDialog(props.row)" >
              <q-tooltip>删除</q-tooltip>
            </q-btn>
            <q-toggle
              v-model="props.row.companyStatus"
              true-value="1" false-value="2"
              checked-icon="iconfont icontubiao-49"
              unchecked-icon="iconfont icontubiao-48"
              :disable="isStatusToggleDisabled[props.row.id]"
              color="positive"
              @input="onStatusToggle(props.row)"
            >
              <template v-slot>
                <q-tooltip>启用/封禁</q-tooltip>
              </template>
            </q-toggle>
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <pagination v-model="myPagination.pageCur" :page-size="myPagination.pageSize" :total="myPagination.total"
                @changePage="pageChange" @changePageSize="changePageSize"></pagination>
  </div>

  <company-dialog ref="companyDialog" :statusOptions="statusOptions" @submit="onsubmit"></company-dialog>
</div>
</template>

<script>
import SelectInput from 'src/components/select-input'
import Collapse from 'src/components/collapse'
import Pagination from 'src/components/pagination'
import CompanyDialog from './components/company-dialog'
import { getCompany, addCompany, editCompany, editStatus, delCompany } from 'src/boot/bms/company'
import { getDictlistByCode } from 'src/boot/bms/bms-dict'
import refreshMixin from '../../assets/js/refresh-mixin'

export default {
  name: 'company-list',
  mixins: [refreshMixin],
  data () {
    return {
      statusOptions: [], // 企业状态列表
      isStatusOptionsLoading: false, // 企业状态加载
      // 查询参数
      queryParams: {
        administrator: '', // 管理员
        name: '', // 企业名称
        status: null // 企业状态
      },
      // 关键字查询条件
      queryConditions: [
        { id: 'name', name: '企业名称' },
        { id: 'administrator', name: '管理员账号' }
      ],
      // table
      tableLoading: false, // table加载时使用
      tableData: [], // table数据
      columns: [ // 所有标题
        { name: 'name', align: 'left', label: '企业名称', field: 'calories', sortable: true },
        { name: 'administrator', align: 'left', label: '管理员账户', field: 'fat', sortable: true },
        { name: 'email', align: 'center', label: '邮箱', field: 'carbs' },
        { name: 'statusLabel', align: 'center', label: '状态', field: 'protein' },
        { name: 'operate', align: 'center', label: '操作', field: 'sodium' }
      ],
      selected: [], // 选中的数据
      // 分页
      myPagination: {
        pageCur: 1, // 页码
        pageSize: 15, // 每页多少条
        total: 0, // 一共多少条
        sortBy: 'id',
        descending: 'asc' // asc 正序 desc 倒叙
      },
      isStatusToggleDisabled: {}
    }
  },
  created () {
    this.getCompanyStatus()
    this.getCompanyList()
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.queryParams.status = null
      this.myPagination.pageCur = 1
      this.myPagination.pageSize = 15
      this.myPagination.sortBy = 'id'
      this.myPagination.descending = 'asc'
      this.$refs.collapse.isActive = true
      this.getCompanyStatus()
      this.$refs.selectInput.clearSearchVal()
    },
    getCompanyStatus () {
      this.isStatusOptionsLoading = true
      // 获取企业状态列表
      getDictlistByCode('company_status').then((res) => {
        this.statusOptions = [{ label: '全部', value: null }]
        let statusOptions = res.data.filter(item => {
          return item.enableFlag
        })
        this.statusOptions.push(...statusOptions)
      }).finally(() => {
        this.isStatusOptionsLoading = false
      })
    },
    // 获取企业列表
    getCompanyList () {
      console.log(this.queryParams)
      let info = {
        administrator: this.queryParams.administrator,
        name: this.queryParams.name,
        companyStatus: this.queryParams.status,
        pageNum: this.myPagination.pageCur,
        pageSize: this.myPagination.pageSize,
        sortName: this.myPagination.sortBy,
        sortOrder: this.myPagination.descending
      }
      this.tableLoading = true
      // 获取企业列表
      getCompany(info).then((res) => {
        this.tableData = res.data.list
        this.myPagination.total = res.data.total
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 翻页
    pageChange (page) {
      this.myPagination.pageCur = page
      this.getCompanyList()
    },
    // 更换每页多少条
    changePageSize (pageSize, page) {
      this.myPagination.pageSize = pageSize
      page && (this.myPagination.pageCur = page)
      this.getCompanyList()
    },
    // 搜索
    onSearchByFilters () {
      this.myPagination.pageCur = 1
      this.getCompanyList()
    },
    /**
     * 重置搜索栏
     */
    resetSearch: function () {
      this.queryParams.status = null
    },
    /**
     * on 批量删除按钮被点击
     */
    onBatchDeleteClick: function () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除这些用户吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        let ids = this.selected.map(item => {
          return item.id
        })
        delCompany(ids).then(res => {
          this.getCompanyList()
          this.$message.success('删除企业成功')
        })
      })
    },
    /**
     * on 关键字搜索
     * 按筛选条件 + 关键字进行列举
     */
    onSearchByKeyword: function (searchBy, keyword) {
      this.queryConditions.forEach(item => {
        this.queryParams[item.id] = ''
      })
      this.queryParams[searchBy.id] = keyword
      this.myPagination.pageCur = 1
      this.getCompanyList()
    },
    /**
     * 重置搜索条件
     */
    clearSearchVal () {
      this.queryParams.administrator = null
      this.queryParams.name = null
      this.myPagination.pageCur = 1
      this.getCompanyList()
    },
    // 打开编辑和新增弹框
    openCompanyDialog (state, item) {
      this.dialogState = state
      this.dialogInfo = item
      this.$refs.companyDialog.showDialog(state, item)
    },
    // 提交弹框
    onsubmit (info, id) {
      console.log(id)
      if (this.dialogState === 'add') {
        addCompany(info).then((res) => {
          this.$refs.companyDialog.hideDialog()
          this.getCompanyList()
          this.$message.success('添加成功')
        }).finally(() => {
          this.$refs.companyDialog.submitting = false
        })
      } else {
        editCompany(info, id).then((res) => {
          this.$refs.companyDialog.submitting = false
          this.$refs.companyDialog.hideDialog()
          this.getCompanyList()
          this.$message.success('编辑成功')
        }).finally(() => {
          this.$refs.companyDialog.submitting = false
        })
      }
    },
    // 删除一条
    delDialog (item) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除此项吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        delCompany([item.id]).then(res => {
          this.getCompanyList()
          this.$message.success(`删除企业${item.name}成功`)
        })
      })
    },
    // 切换企业禁用/启用状态
    onStatusToggle (val) {
      this.$set(this.isStatusToggleDisabled, val.id, true)
      let params = {
        status: val.companyStatus
      }
      console.log(val)
      console.log(params)
      editStatus(val.id, params).then(() => {
        this.getCompanyList()
      }).finally(() => {
        this.$set(this.isStatusToggleDisabled, val.id, false)
      })
    }
  },
  components: {
    CompanyDialog,
    SelectInput,
    Pagination,
    Collapse
  }
}
</script>

<style scoped lang='stylus'>
.company-list{
  border-radius 6px;
  padding-bottom 20px;
  position relative;
}
</style>
<style lang="stylus">
  .company-list{
    .myTable .q-table__middle{
      max-height calc(100% - 42px)
    }
  }
</style>
